//
//  XS_MineVC.swift
//  XueDao
//
//  Created by fandongtongxue on 2020/12/8.
//

import UIKit

class XS_MineVC: XS_BaseVC {

    @IBOutlet weak var tableView: UITableView!
    var model : XS_UserBOM?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        model = XS_Singleton.shared.infoModel?.userBO
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib.init(nibName: "XS_MineTopCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_MineTopCell")
        tableView.register(UINib.init(nibName: "XS_MineCell", bundle: Bundle.main), forCellReuseIdentifier: "XS_MineCell")
        #if DEBUG
        showBuildVersion()
        #endif
        
//        let buildVer = buildVersionView(test: true)
//        buildVer.frame.origin.y = UIScreen.main.bounds.size.height - ((UIApplication.shared.statusBarFrame.height == 44) ? 83 : 49) - buildVer.frame.size.height
    }
    
    func showBuildVersion() {
        let longPress = UILongPressGestureRecognizer.init(target: self, action: #selector(showBuildVer(longPress:)))
        longPress.minimumPressDuration = 3.0
        longPress.numberOfTouchesRequired = 1
        tabBarController?.tabBar.addGestureRecognizer(longPress)
    }
    
    @objc func showBuildVer(longPress: UILongPressGestureRecognizer) {
        if longPress.state ==  UIGestureRecognizer.State.began {
            let test: Bool = false
            let buildVer = buildVersionView(test: test)
            UIView.animate(withDuration: 1) {
                buildVer.frame.origin.y = UIScreen.main.bounds.size.height - ((UIApplication.shared.statusBarFrame.height == 44) ? 83 : 49) - buildVer.frame.size.height
            } completion: { (success) in
                if test == false {
                    UIView.animate(withDuration: 2, delay: 5, options: .curveEaseInOut) {
                        buildVer.frame.origin.y = UIScreen.main.bounds.size.height
                    } completion: { (success) in
                        buildVer.removeFromSuperview()
                    }
                }
            }
        }
    }
    
    func buildVersionView(test: Bool) -> UILabel {
        let buildVerLab = UILabel()
        buildVerLab.backgroundColor = UIColor.lightGray.withAlphaComponent(0.2)
        buildVerLab.textAlignment = .center
        buildVerLab.textColor = .orange
        buildVerLab.text = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
        buildVerLab.frame = CGRect.init(x: UIScreen.main.bounds.size.width / 2, y: UIScreen.main.bounds.size.height, width: UIScreen.main.bounds.size.width / 2, height: 45)
        view.addSubview(buildVerLab)
        view.bringSubviewToFront(buildVerLab)
        if test {
            buildVerLab.isUserInteractionEnabled = true
            let tapGes = UITapGestureRecognizer.init(target: self, action: #selector(testBtnClick))
            buildVerLab.addGestureRecognizer(tapGes)
        }
        return buildVerLab
    }
    
    @objc func testBtnClick() {
//        let admVc = XS_AdmissionVC()
//        navigationController?.pushViewController(admVc, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        requestData()
        self.tabBarController?.tabBar.unselectedItemTintColor = #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1)
    }


    func requestData(){
        XS_NetWork.requestJson("/user/getCurrUser")
            .mapModel(type: XS_UserBOM.self) // 返回 模型对象 和原始数据
            .subscribe(onNext: { model, resp in
                XS_Singleton.shared.infoModel?.userBO = model!
                self.model = model
                //未读计数
                XS_NetWork.requestJson("/notice/queryNotReadNum")
                    .filter({$0.success})
                    .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                        let count = resp.data as! Int
                        self.model?.unreadCount = count
                        self.tableView.reloadData()
                    }).disposed(by: self.disposeBag)
            }).disposed(by: disposeBag)
    }

}
extension XS_MineVC : UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "XS_MineTopCell", for: indexPath) as! XS_MineTopCell
            cell.delegate = self
            if model != nil {
                cell.model = model
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "XS_MineCell", for: indexPath) as! XS_MineCell
        let titleArr = ["邀请好友","我的助教","设置"]
        cell.leftTitleLabel.text = titleArr[indexPath.row - 1]
        cell.leftImageView.image = UIImage.init(named: "icon_16_"+titleArr[indexPath.row - 1])
        if indexPath.row == 1 {
            cell.rightTitleLabel.text = "邀请好友领学到币"
        }
        cell.rightTitleLabel.isHidden = indexPath.row != 1
        cell.redPointView.isHidden = indexPath.row != 1
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 350 + CGFloat.barHeight
        }
        return 50
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 3:
            let setVC = XS_SetVC()
            setVC.model = model
            navigationController?.pushViewController(setVC, animated: true)
            break
        case 2:
//            let assistantsVC = XS_MineAssistantsVC()
//            navigationController?.pushViewController(assistantsVC, animated: true)
            
            let qidianUrl = "https://wpa1.qq.com/gPNerizz?_type=wpa&qidian=true"
//            let qidianUrl = "http://xdapp.yaoxuedao.com.cn/specialActivities?id=7"
            let webVC = XS_WebPageVC()
            webVC.loadUrl(qidianUrl)
            navigationController?.pushViewController(webVC, animated: true)
            break
        case 1:
            let inviteVC = XS_InviteVC()
            navigationController?.pushViewController(inviteVC, animated: true)
            break
        default:
            break
        }
    }
    
}

extension XS_MineVC : XS_MineTopCellDelegate{
    func topCell(_: XS_MineTopCell, didClickInfoBtn: UIButton) {
        let infoVC = XS_MineInfoVC()
        navigationController?.pushViewController(infoVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickNotificationBtn didClickotificationBtn: UIButton) {
        let notificationVC = XS_NotificationVC()
        navigationController?.pushViewController(notificationVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickVipBtn: UIImageView) {
        let vipVC = XS_VIPVC()
        navigationController?.pushViewController(vipVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickFavoriteBtn: QMUIButton) {
        let favoriteVC = XS_FavoriteVC()
        navigationController?.pushViewController(favoriteVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickApplyBtn: QMUIButton) {
//        let applyVC = XS_ApplyVC()
//        navigationController?.pushViewController(applyVC, animated: true)
        self.view.makeToast("报名系统正在升级，敬请期待")
    }
    
    func topCell(_: XS_MineTopCell, didClickCertBtn: QMUIButton) {
        let certVC = XS_CertVC()
        navigationController?.pushViewController(certVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickOrderBtn: QMUIButton) {
        let orderVC = XS_OrderVC()
        navigationController?.pushViewController(orderVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickIntegralBtn: QMUIButton) {
        let integralVC = XS_IntegralVC()
        navigationController?.pushViewController(integralVC, animated: true)
    }
    
    func topCell(_: XS_MineTopCell, didClickCouponBtn: QMUIButton) {
        let couponVC = XS_CouponVC()
        navigationController?.pushViewController(couponVC, animated: true)
    }
    
}

